package com.hpe.aruba.CPPM;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ShareCompat;
import androidx.core.content.FileProvider;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.hpe.aruba.CPPM.adapter.SwipeListAdapter;
import com.hpe.aruba.CPPM.dialogs.MacAdressDialog;
import com.hpe.aruba.CPPM.dialogs.SortDialog;
import com.hpe.aruba.CPPM.enums.SharedPrefFields;
import com.hpe.aruba.CPPM.interfaces.MacListActivity;
import com.hpe.aruba.CPPM.objects.Device;
import com.hpe.aruba.CPPM.utils.ClearpassUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ManageMacsActivity extends AppCompatActivity
        implements SwipeListAdapter.OnMacListener, MacListActivity,
        RecyclerItemTouchHelper.RecyclerItemTouchHelperListener, SwipeRefreshLayout.OnRefreshListener, NavigationView.OnNavigationItemSelectedListener {

    private static final String TAG = "CLEARPASS";
    private static final String DEVICES = "com.hpe.aruba.CPPM.DEVICES";
    private static final int GET_MACS_ACTIVITY = 0;
    private static final int FILTER_ENDPOINTS = 1;
    private static String[] sortOptions = new String[]{"Scan Time", "Mac", "Vendor"};
    public SearchView searchView;

    ImageButton macArrow;
    ImageButton vendorArrow;
    ImageButton col2Arrow;
    TextView macOrderText;
    TextView vendorOrderText;
    TextView col2OrderText;

    FloatingActionButton fab;
    DrawerLayout drawerLayout;
    NavigationView navigationView;
    ActionBarDrawerToggle drawerToggle;
    TextView urlText;
    String url;

    public SortDialog sortDialog;
    private boolean checkForStatus;
    private int statusRadioNumber;

    private ArrayList<Device> macs; /*Holds the current MacList that is shown in the list */
    public ArrayList<Device> vendorFilterRest; /*Holds all the macs that are taken out of the list by the 'hasVendor' filter*/
    public ArrayList<Device> constrainedMacs; /*Holds all the Macs that are still in the list after filtering*/

    private SwipeListAdapter macListAdapter;
    private Context mContext;
    private boolean order = true;
    private int lastSort = 0;
    private ActivityState currentState;
    private ClearpassUtils clearpassUtils;
    private RequestQueue queue;

    SharedPreferences sharedPreferences;

    private static ManageMacsActivity instance;

    //@BindView(R.id.toolbar)
    //Toolbar toolbar;
    @BindView(R.id.macEditListView)
    RecyclerView mMacListView;
    //@BindView(R.id.macsLayout)
    ConstraintLayout mTopLayout;
    //@BindView(R.id.floatingActionButton)
    //FloatingActionButton mFloatingActionButton;
    SwipeRefreshLayout refreshLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_macs);
        mContext = getApplicationContext();
        ButterKnife.bind(this);

        Toolbar toolbar = findViewById(R.id.incl_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        sharedPreferences =
                PreferenceManager.getDefaultSharedPreferences(this /* Activity context */);

        navigationView = findViewById(R.id.navigationView);
        drawerLayout = findViewById(R.id.drawerLayout);
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawerOpen, R.string.drawerClose);
        drawerLayout.addDrawerListener(drawerToggle);
        drawerToggle.syncState();
        navigationView.setNavigationItemSelectedListener(this::onNavigationItemSelected);
        fab = findViewById(R.id.floatingActionButton);

        constrainedMacs = new ArrayList<>();
        refreshLayout = findViewById(R.id.swiperefresh);
        refreshLayout.setOnRefreshListener(this::onRefresh);

        macs = new ArrayList<>();
        vendorFilterRest = new ArrayList<>();


        macListAdapter = new SwipeListAdapter(this, macs, this);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mMacListView.setLayoutManager(mLayoutManager);
        mMacListView.setItemAnimator(new DefaultItemAnimator());
        //if custom divider is desired:
        /*DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(getResources().getDrawable(R.drawable.divider,null));*/
        mMacListView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mMacListView.setAdapter(macListAdapter);

        queue = Volley.newRequestQueue(this);
        clearpassUtils = new ClearpassUtils(queue);

        ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new RecyclerItemTouchHelper(0, ItemTouchHelper.LEFT, this);
        new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(mMacListView);
        changeState(ActivityState.NORMAL);
        sortList(0);

        boolean loadOnStartup = sharedPreferences.getBoolean("load", true);
        if (loadOnStartup) {
            syncDevices();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GET_MACS_ACTIVITY) {
            if (resultCode == RESULT_OK) {
                macs = data.getParcelableArrayListExtra(DEVICES);
                updateSwipeList(macs);
            }
        }
        else if (requestCode == FILTER_ENDPOINTS){
            if (resultCode == RESULT_OK){
                macs = data.getParcelableArrayListExtra("DEVICES");
                applySharedPreferences();
                onSortActivityResult(false);
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void updateSwipeList(ArrayList<Device> newMacList) {
        macListAdapter = new SwipeListAdapter(this, newMacList, this);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mMacListView.setLayoutManager(mLayoutManager);
        mMacListView.setItemAnimator(new DefaultItemAnimator());
        mMacListView.setAdapter(macListAdapter);
    }

    public void onSortActivityResult(boolean loaded){
        if (loaded) {
            Log.d("xxxxx","Filtering on startup was called");
            performFiltering(checkForStatus);
            updateSwipeList(macs);
            sortList(lastSort);
        } else {
            syncDevices();
        }
    }

    /**
     * Constructor for the Menu in the ActionBar.
     * It is only called once
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        urlText = findViewById(R.id.url_textView);
        if (Data.baseUrl.startsWith("https://")){
            url = Data.baseUrl.substring("https://".length());
            urlText.setText(url);
        } else if (Data.baseUrl.startsWith("http://")) {
            url = Data.baseUrl.substring("http://".length());
            urlText.setText(url);
        } else {
            url = Data.baseUrl;
            urlText.setText(url);
        }
        // Inflate the menu.
        getMenuInflater().inflate(R.menu.menu_list, menu);

        /**Inflates SearchBar if activated and filters the mac DB depending on newText's constraints*/
        MenuItem searchItem = menu.findItem(R.id.app_bar_search);
        searchView = (SearchView) searchItem.getActionView();
        searchView.setQueryHint(getResources().getString(R.string.queryHint));
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                macListAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                macListAdapter.getFilter().filter(newText);
                return false;
            }
        });
        return true;
    }

    /**Modifies the OptionMenu, if invalidateOptionsMenu() is called.
     * It is used to alter the menu depending on whether Endpoints or Devices are shown
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
        MenuItem filterItem = menu.findItem(R.id.filter);
        AppCompatTextView title = findViewById(R.id.domain);
        TextView col2Header = findViewById(R.id.orderTextCol2);
        if (currentState==ActivityState.NORMAL){
            filterItem.setVisible(false);
            title.setText(getResources().getString(R.string.endpoints));
            col2Header.setText(getResources().getString(R.string.status));
            applySharedPreferences();
        } else if (currentState==ActivityState.GUEST){
            filterItem.setVisible(true);
            title.setText(getResources().getString(R.string.guest_devices));
            col2Header.setText(getResources().getString(R.string.role));
            applySharedPreferences();
        }
        return super.onPrepareOptionsMenu(menu);
    }

    /**changeState() switches between the Devices and Endpoint view, therefore changing menuItems, drawables and the header text.
     * TODO: Implement different Mac Lists depending on the context (filled with Endpoints or Devices) and changes filter options
     * @param state
     */
    private void changeState(ActivityState state) {
        currentState = state;
        switch (state) {
            case NORMAL:
                //macListAdapter.showCheckboxes(false);
                //mFloatingActionButton.setOnClickListener(this::uploadAddresses);
                //mFloatingActionButton.setImageResource(android.R.drawable.ic_menu_upload);
                macListAdapter.setOnMacListener(this);
                fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_filter_list_black_24dp, null));
                invalidateOptionsMenu();
                syncDevices();
                break;
            /*case BATCH_EDIT:
                macListAdapter.showCheckboxes(true);
                //mFloatingActionButton.setOnClickListener(v -> new BatchEditDialog(this, new Device("BATCH")).show());
                //mFloatingActionButton.setImageResource(android.R.drawable.ic_menu_edit);
                macListAdapter.setOnMacListener(position -> macListAdapter.getItemAt(position));
                break;*/
            case GUEST:
                //TODO: Change to Guest Devices: other list, other filter, other menu items, other FAB
                fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_add_24dp, null));
                invalidateOptionsMenu();
                syncDevices();
                break;
        }
    }

    public void applySharedPreferences(){
        if(currentState == ActivityState.NORMAL){
            order = sharedPreferences.getBoolean(SharedPrefFields.ENDPOINT_SORT.ORDER.toString(), false);
            checkForStatus = sharedPreferences.getBoolean(SharedPrefFields.ENDPOINT_SORT.STATUS_FILTER_CHECKED.toString(), false);
            statusRadioNumber = sharedPreferences.getInt(SharedPrefFields.ENDPOINT_SORT.STATUS_RADIO_NUMBER.toString(), 0);
            lastSort = sharedPreferences.getInt(SharedPrefFields.ENDPOINT_SORT.SORT_RADIO_NUMBER.toString(), 0);
        } else if (currentState == ActivityState.GUEST){
            //Put sharedPreferences for Guest Devices here
        }
    }

    @Override
    public void onBackPressed() {
        if (currentState != ActivityState.NORMAL) {
            changeState(ActivityState.NORMAL);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            startActivity(new Intent(this, SettingsActivity.class));
        /*} else if (id == R.id.sort_by) {
            new AlertDialog.Builder(this)
                    .setSingleChoiceItems(sortOptions, lastSort, (d, n) -> {
                        d.dismiss();
                        sortList(n);
                    })
                    .setTitle("Sort by").show();
        } else if (id == R.id.option) {
            order = !order;
            item.setIcon(order ? android.R.drawable.arrow_up_float : android.R.drawable.arrow_down_float);
            sortList(lastSort);
        } else if (id == R.id.action_batch_edit) {
            changeState(ActivityState.BATCH_EDIT);*/
        }
        /** Sort Options in sort_by optionsmenu */
        else if (id == R.id.sort_mac) {
            sortList(0);
        } else if (id == R.id.sort_date_added) {
            sortList(1);
        } else if (id == R.id.sort_vendor) {
            sortList(2);
        } else if (id == R.id.sync_devices) {
            if (searchView.isIconified()) {/**Doesn't sync devices, if searchbar is expanded, due to bug in search functionality*/
                syncDevices();
                Log.d("CLEARPASS", "sync performed");
            }
        } else if (id == R.id.action_logout) {
            logout();
        } else if (id == R.id.export) {
            exportDevices();
        } else if (id == R.id.filter) {
            sortDialog = new SortDialog(this, macs);
            sortDialog.show();
        }
        return super.onOptionsItemSelected(item);
    }

    private void exportDevices() {
        ProgressDialog progressDialog = new ProgressDialog(this,
                R.style.AppTheme_Dark_Dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Processing...");
        progressDialog.show();

        File cacheFile;
        try {
            cacheFile = File.createTempFile("devices_", ".csv", getCacheDir());
            FileOutputStream fos = new FileOutputStream(cacheFile);
            try {
                for (Device mac : macs) {
                    fos.write(mac.getMac().getBytes());
                    fos.write("\n".getBytes());
                }

            } finally {
                fos.close();
            }
            Uri uri = FileProvider.getUriForFile(this, "com.hpe.aruba.CPPM.provider", cacheFile);

            Intent intent = ShareCompat.IntentBuilder.from(this)
                    .setType("text/csv")
                    .setSubject(getString(R.string.share_subject))
                    .setStream(uri)
                    .setChooserTitle(R.string.share_title)
                    .createChooserIntent()
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
            progressDialog.dismiss();
        } catch (IOException e) {
            Toast.makeText(mContext, "an error occured...", Toast.LENGTH_LONG).show();
        }
    }

    private void logout() {
        SharedPreferences.Editor edit = Data.sharedPreferences.edit();
        edit.remove(SharedPrefFields.TOKEN.toString());
        edit.remove(SharedPrefFields.TOKEN_EXP.toString());
        edit.apply();

        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
        finish();
    }

    public void sortList(int n) {
        /**sorts the Mac List in direction of time_created (n=0), mac_address (n=1), Vendor (n=2)
         * warning: compareTo() does not take in null e.g. mac without time_created would cause a runtime failure
         */
        lastSort = n;
        Comparator<Device> comparator = (o1, o2) -> o1.getMac().compareTo(o2.getMac());
        switch (n) {
            case 0:
                comparator = (o1, o2) -> o1.getMac().compareTo(o2.getMac());
                break;
            case 1:
                comparator = (o1, o2) -> {
                    //If both o1 and o2 have a creation time, then compare normally
                    if(o1.getCreation()!= 0 && o2.getCreation()!= 0){
                        return Long.compare(o1.getCreation(), o2.getCreation());
                    }
                    //o1>o2; o1 has a higher rank than o2
                    else if (o1.getCreation() != 0 && o2.getCreation() == 0) {
                        return 1;
                    }
                    //o1<o2; o1 has a lower rank than o2
                    else if (o1.getCreation() == 0 && o2.getCreation() != 0) {
                        return -1;
                    }
                    //neither o1 nor o2 has has a creation time; same rank
                    else {
                        return 0;
                    }
                };
                break;
            case 2:
                comparator = (o1, o2) -> {
                    //Compare Vendor normally
                    if (o1.getVendor() != null && o2.getVendor() != null) {
                        return o1.getVendor().compareTo(o2.getVendor());
                    }
                    //o1>o2; o1 has a higher rank than o2
                    else if (o1.getVendor() != null && o2.getVendor() == null) {
                        return 1;
                    }
                    //o1<o2; o1 has a lower rank than o2
                    else if (o1.getVendor() == null && o2.getVendor() != null) {
                        return -1;
                    }
                    //Neither contains a vendor, so they are the same rank: 0
                    else {
                        return 0;
                    }
                };
                break;
        }

        macs.sort(order ? comparator : comparator.reversed());
        updateMac();
    }

    public void changeOrder(View view) {
        order = !order;
        ImageButton sort_arrow = (ImageButton) view;
        sort_arrow.setImageDrawable(getResources().getDrawable((order ? R.drawable.ic_arrow_down_24dp : R.drawable.ic_arrow_up_24dp), null));
    }

    public void changeActiveSortElement(@Nullable View view){
        macArrow = findViewById(R.id.arrowSortMac);
        vendorArrow = findViewById(R.id.arrowSortVendor);
        col2Arrow = findViewById(R.id.arrowSortCol2);
        macOrderText = findViewById(R.id.orderTextMac);
        vendorOrderText = findViewById(R.id.orderTextVendor);
        col2OrderText = findViewById(R.id.orderTextCol2);
        if (view == null){
            setColorGrey(null);
            order = true;
        } else {
            setColorGrey(view);
        }
    }

    public void setColorGrey(View exception){
        if(!(exception == macArrow || exception == macOrderText)){
            macArrow.setImageDrawable(getResources().getDrawable(R.drawable.ic_arrow_down_grey_24dp, null));
            macOrderText.setTextColor(getResources().getColor(R.color.aruba_grey,null));
            macOrderText.setTypeface(null, Typeface.NORMAL);
        } else {
            macOrderText.setTextColor(getResources().getColor(R.color.black,null));
            macOrderText.setTypeface(null, Typeface.BOLD);
        }
        if (!(exception == vendorArrow || exception == vendorOrderText)){
            vendorArrow.setImageDrawable(getResources().getDrawable(R.drawable.ic_arrow_down_grey_24dp, null));
            vendorOrderText.setTextColor(getResources().getColor(R.color.aruba_grey,null));
            vendorOrderText.setTypeface(null, Typeface.NORMAL);
        } else {
            vendorOrderText.setTextColor(getResources().getColor(R.color.black,null));
            vendorOrderText.setTypeface(null, Typeface.BOLD);
        }
        if(!(exception == col2Arrow || exception == col2OrderText)){
            col2Arrow.setImageDrawable(getResources().getDrawable(R.drawable.ic_arrow_down_grey_24dp, null));
            col2OrderText.setTextColor(getResources().getColor(R.color.aruba_grey,null));
            col2OrderText.setTypeface(null, Typeface.NORMAL);
        } else {
            col2OrderText.setTextColor(getResources().getColor(R.color.black,null));
            col2OrderText.setTypeface(null, Typeface.BOLD);
        }
    }

    public int getLastSort() {
        return lastSort;
    }

    @Override
    public void onMacClicked(int position) {
        Device device = macs.get(position);
        MacAdressDialog mad = new MacAdressDialog(this, device);
        mad.show();
    }

    @Override
    public void updateMac() {
        macListAdapter.notifyDataSetChanged();
    }

    public void uploadAddresses(View view) {
        clearpassUtils.createDevices(macs, this);

        Snackbar.make(view, "Uploading Data...", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
    }

    public void onFabClicked(View view){
        if (currentState==ActivityState.NORMAL){
            Intent intent = new Intent(this, SortEndpointsActivity.class);
            intent.putParcelableArrayListExtra(DEVICES, macs);
            intent.putParcelableArrayListExtra("VENDORFILTERREST", vendorFilterRest);
            intent.putParcelableArrayListExtra("STATIC_MACS", getStaticMacList());
            intent.putExtra("LAST_SORT", lastSort);
            intent.putExtra("ORDER", order);
            startActivityForResult(intent, FILTER_ENDPOINTS);
        } else if (currentState == ActivityState.GUEST){
            addDevice();
        }
    }
    /**
     * Starts the "NewDeviceActivity"
     */
    public void addDevice() {
        Intent intent = new Intent(this, NewDeviceActivity.class);
        intent.putParcelableArrayListExtra(DEVICES, macs); /*add list of macs to intent*/

        startActivityForResult(intent, GET_MACS_ACTIVITY);

    }

    /*callback for swipe to refresh*/
    public void onRefresh() {
        syncDevices();
    }

    /**
     * Downloads devices via getDevices, which calls processDevices with the result.
     * Also handels refreshing display.
     */
    public void syncDevices(MenuItem menuItem) {
        /*gets the swipe refresh layout*/
        refreshLayout.setRefreshing(true);
        /*download devices and call processDevices*/
        if (currentState == ActivityState.NORMAL){
            byte progress = (byte) sharedPreferences.getInt("GET_UNTIL_SELECTION", 7);
            long getUntil = SortEndpointsActivity.getUnixTimeStampFromProgress(progress).getTime()/1000L;
            clearpassUtils.getEndpointsSince(getUntil, this);
        } else if (currentState == ActivityState.GUEST){
            clearpassUtils.getDevices(this);
        }
    }

    public void syncDevices() {
        syncDevices(null);
    }


    /**
     * Adds new devices from getDevices/cppm
     */
    public void processDevices(List<Device> devices) {
        macs.clear();
        for (Device device : devices) {
            macs.add(device);
        }
        updateSwipeList(macs);
        refreshLayout.setRefreshing(false);
        /**sets a static list of macs, so that search results can be undone, when the search is closed*/
        macListAdapter.setStaticMacs(macs);

        if(currentState == ActivityState.NORMAL){onSortActivityResult(true);}

        changeActiveSortElement(null);
    }


    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
        if (viewHolder instanceof SwipeListAdapter.MyViewHolder) {
            // get the removed item name to display it in snack bar
            Device device = macs.get(viewHolder.getAdapterPosition());

            // backup of removed item for undo purpose
            final Device deletedItem = macs.get(viewHolder.getAdapterPosition());
            final int deletedIndex = viewHolder.getAdapterPosition();

            // remove the item from recycler view
            macListAdapter.removeItem(viewHolder.getAdapterPosition());
//            updateCount();

            if (device.isImported()) {
                AlertDialog confirmationDialogBox = new AlertDialog.Builder(this)
                        .setTitle("Delete")
                        .setMessage("Do you want to Delete")
//                    .setIcon(R.drawable.delete)

                        .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                clearpassUtils.deleteDevice(device);
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                macListAdapter.restoreItem(deletedItem, deletedIndex);
                                dialog.dismiss();
                            }
                        })
                        .create();
                confirmationDialogBox.show();
            } else {
                // showing snack bar with Undo option
                Snackbar snackbar = Snackbar
                        .make(mTopLayout, device.getMac() + " " + getString(R.string.removed), Snackbar.LENGTH_LONG);
                snackbar.setAction("UNDO", view -> {
                    // undo is selected, restore the deleted item
                    macListAdapter.restoreItem(deletedItem, deletedIndex);
                });
                snackbar.setActionTextColor(getColor(R.color.aruba_orange));
                snackbar.show();
            }
        }
    }

    public void onCheckboxClicked(View view) {
        sortDialog.onCheckboxClicked(view);
    }


    public void resetMacs() {
        macs.clear();
        macs.addAll(getStaticMacList());
        Log.d("xxxxxxxxxx", "Macs were reset to " + macs);
        macListAdapter.notifyDataSetChanged();
    }

    public ArrayList<Device> getMacs() {
        return macs;
    }

    public ArrayList<Device> getStaticMacList() {
        return macListAdapter.getStaticMacs();
    }

    public SwipeListAdapter getListAdapter() {
        return this.macListAdapter;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.burger_devices:
                changeState(ActivityState.GUEST);
                drawerLayout.closeDrawers();
                break;
            case R.id.burger_endpoints:
                changeState(ActivityState.NORMAL);
                drawerLayout.closeDrawers();
                break;
            case R.id.burger_batch_scan:
                Intent intent = new Intent(this, MultiTrackerActivity.class);
                intent.putParcelableArrayListExtra(DEVICES, macs); /*add list of macs to intent*/
                startActivity(intent);
                drawerLayout.closeDrawers();
                break;
            case R.id.burger_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                drawerLayout.closeDrawers();
                break;
            case R.id.burger_export:
                exportDevices();
                drawerLayout.closeDrawers();
                break;
            case R.id.burger_logout:
                logout();
                drawerLayout.closeDrawers();
                break;
        }
        return false;
    }

    public void onOrderBarItemSelected(View view){
        int id = view.getId();
        switch (id){
            case (R.id.arrowSortMac):
                changeActiveSortElement(view);
                changeOrder(view);
                sortList(0);
                break;
            case (R.id.arrowSortVendor):
                changeActiveSortElement(view);
                changeOrder(view);
                sortList(2);
                break;
            case (R.id.arrowSortCol2):
                changeActiveSortElement(view);
                changeOrder(view);
                if (currentState == ActivityState.GUEST){
                    sortList(0);//TODO: change to role filter
                } else {
                    sortList(0);//TODO: change to status filter
                }
                break;
        }

    }



    public void performFiltering(boolean checkForStatus){
        //sets back all the filters, by putting all synced macs in the list, thus overwriting current filters
        macs = new ArrayList<>(getStaticMacList());
        //currentMacs is a copy of the macs list during every filter procedure
        ArrayList<Device> currentMacs = new ArrayList<>(getStaticMacList());

        //applying the selected filters
        if (checkForStatus) {
            //TODO:Filter for appropriate MACS here
            switch(statusRadioNumber){
                case 0:
                    statusFilter("Known", currentMacs);
                    break;
                case 1:
                    statusFilter("Unknown", currentMacs);
                    break;
                case 2:
                    statusFilter("Disabled", currentMacs);
                    break;
                default:
                    break;
                }
            }
        }

    /**FILTERS*/

    private void vendorFilter(ArrayList<Device> currentMacs){
        macs.clear();
        for(Device mac : currentMacs){
            if (mac.getVendor() != null && !mac.getVendor().equals("")){
                macs.add(mac);
            }
        }
        currentMacs.clear();
        currentMacs.addAll(macs);
    }

    private void statusFilter(String constraint,ArrayList<Device> currentMacs){
        macs.clear();
        for (Device mac: currentMacs){
            if (mac.getStatus().equals(constraint)){
                macs.add(mac);
            }
        }
        currentMacs.clear();
        currentMacs.addAll(macs);
    }
}
